package com.silence.gmall.product.service.impl;

import com.alibaba.fastjson2.JSON;
import com.silence.gmall.annotation.MallCache;
import com.silence.gmall.constant.ProductRedisStringConstant;
import com.silence.gmall.product.domain.repository.BaseCategory1Repository;
import com.silence.gmall.product.service.CategoryService;
import com.silence.gmall.web.vo.res.CategoryResVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author silence
 * @Date 2025-09-05 15:06
 * @Email 792245022@qq.com
 * @Version 1.0
 * @Description 分类服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CategoryServiceImpl implements CategoryService {

    /**
     * BaseCategory1Repository 的注入
     */
    private final BaseCategory1Repository baseCategory1Repository;

    /**
     * StringRedisTemplate 的注入
     */
    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 查询所有分类
     *
     * @return 所有分类树形结构
     */
    @MallCache(cacheKey = ProductRedisStringConstant.PRODUCT_CATEGORY_TREE_REDIS_KEY)
    @Override
    public List<CategoryResVo> getCategoryTree() {
        // 获取 redis key
        String categoryTreeKey = stringRedisTemplate.opsForValue().get(ProductRedisStringConstant.PRODUCT_CATEGORY_TREE_REDIS_KEY);

        // 如果 redis 中存在分类树，则直接返回
        if (StringUtils.isNotBlank(categoryTreeKey)) {
            log.info("从 Redis 中获取分类树");
            return JSON.parseArray(categoryTreeKey, CategoryResVo.class);
        }

        // 如果不存在，查询数据库
        List<CategoryResVo> categoryTree = baseCategory1Repository.getCategoryTree();
        stringRedisTemplate.opsForValue().set(ProductRedisStringConstant.PRODUCT_CATEGORY_TREE_REDIS_KEY, JSON.toJSONString(categoryTree));
        return categoryTree;
    }
}
